package com.irun.cm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.irun.cm.vo.SMSItem;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.QuickContact;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/***
 * @author huangsm
 * @date 2012-5-12
 * @email huangsanm@gmail.com
 * @description sms adapter
 */
public class MessageListItemAdapter extends BaseAdapter {
	private final static float ROUND = 20.0f;
	private final static String SMS_URI = "content://sms/";
	
	//id
	private final static String ID = "_id";
	//序号，同一发信人的id相同
	private final static String THREAD_ID = "thread_id";
	//联系人列表里的序号，陌生人为null 
	private final static String PERSON = "person";
	//发件日期
	private final static String DATE = "date";
	//电话号码
	private final static String ADDRESS = "address";
	//read是否阅读 0未读， 1已读
	private final static String READ = "read";
	//类型ALL=0;INBOX=1;SENT=2;DRAFT=3;OUTBOX=4;FAILED=5;QUEUED=6
	private final static String TYPE = "type";
	//短信内容
	private final static String BODY = "body";
	
	private ArrayList<SMSItem> messages;
	private Context mContext;
	private LayoutInflater mInflater;
	private ContentResolver mResolver;
	public MessageListItemAdapter(Context context){
		mContext = context;
		mResolver = mContext.getContentResolver();
		mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		messages = getMessageList();
		System.out.println("size: " + messages.size());
	}
	
	@Override
	public int getCount() {
		return messages.size();
	}

	@Override
	public Object getItem(int position) {
		return messages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if(convertView == null){
			convertView = mInflater.inflate(R.layout.message_item, null);
			holder = new ViewHolder();
			holder.header = (ImageView) convertView.findViewById(R.id.msg_head);
			holder.name = (TextView) convertView.findViewById(R.id.msg_name);
			holder.date = (TextView) convertView.findViewById(R.id.msg_date);
			holder.content = (TextView) convertView.findViewById(R.id.msg_content);
			convertView.setTag(holder);
		}else{
			holder = (ViewHolder) convertView.getTag();
		}
		
		final SMSItem item = messages.get(position);
		final PeopleInfo info = getPersonNameByAddress(item.getAddress());
		holder.header.setImageBitmap(info.getPhotos(info.photos));
		holder.header.setOnClickListener(new ImageView.OnClickListener(){
			@Override
			public void onClick(View v) {
				//Uri quickUri = ContactsContract.Contacts.getLookupUri((long) item.getId(), info.lookUpKey);
				//QuickContact.showQuickContact(mContext, holder.header, quickUri, QuickContact.MODE_SMALL, null);
				QuickContactWindow quickContact = new QuickContactWindow(mContext, info.isUnknow);
				quickContact.show(v, -2, -2);
			}
		});
		holder.name.setText(info.displayName);
		holder.date.setText(getDateStr(item.getDate()));
		holder.content.setText(item.getBody().length() > 39 ? item.getBody().subSequence(0, 35) : item.getBody());
		return convertView;
	}
	
	//获取所有信息
	private ArrayList<SMSItem> getMessageList(){
		ArrayList<SMSItem> list = new ArrayList<SMSItem>();
		String[] projection = {ID, THREAD_ID, PERSON, DATE, ADDRESS, READ, TYPE, BODY};
		String selection = "1=1) and type in(1,2) group by (" + THREAD_ID + "";
		String sortOrder = "date desc";
		Cursor cursor = mResolver.query(Uri.parse(SMS_URI), projection, selection, null, sortOrder);
		//由activity管理
		//mSmslist.startManagingCursor(cursor);
		if(cursor != null && cursor.moveToNext()){
			int id = cursor.getColumnIndex(ID);
			int thread_id = cursor.getColumnIndex(THREAD_ID);
			int person = cursor.getColumnIndex(PERSON);
			int date = cursor.getColumnIndex(DATE);
			int address = cursor.getColumnIndex(ADDRESS);
			int type = cursor.getColumnIndex(TYPE);
			int body = cursor.getColumnIndex(BODY);
			
			do {
				SMSItem item = new SMSItem();
				item.setId(cursor.getInt(id));
				item.setThreadID(cursor.getInt(thread_id));
				item.setPerson(cursor.getInt(person));
				item.setDate(cursor.getLong(date));
				item.setAddress(cursor.getString(address));
				item.setType(cursor.getInt(type));
				item.setBody(cursor.getString(body));
				list.add(item);
			} while (cursor.moveToNext());
			cursor.close();
		}
		return list;
	}
	
	private String getDateStr(Object date){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(Long.valueOf(date.toString()));
		Date d = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		return sdf.format(d);
	}
	
	/**
	 * @author huangsm
	 * @date 2012-5-5
	 * @email huangsanm@gmail.com
	 * @description 电话号码转换为联系人姓名
	 */
	private PeopleInfo getPersonNameByAddress(String address){
		PeopleInfo info = new PeopleInfo();
		String args = address;
		if(address.indexOf("+") >= 0)
			args = args + "," + address.substring(3, address.length());
		
		Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, args);
		String[] projection = 
				new String[]{ContactsContract.Contacts.DISPLAY_NAME, 
				ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.PHOTO_ID};
		Cursor cursor = mResolver.query(uri, projection, null, null, null);
		if(cursor != null && cursor.moveToFirst()){
			int columnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
			int lookupKey = cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
			int photoid = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID);
			address = cursor.getString(columnIndex);
			info.lookUpKey = cursor.getString(lookupKey);
			String photo = cursor.getString(photoid);
			if(!TextUtils.isEmpty(photo)){
				Cursor photoCursor = null;
				try {
					photoCursor = mResolver.
							query(ContactsContract.Data.CONTENT_URI, 
									new String[]{ContactsContract.Data.DATA15}, 
									"ContactsContract.Data._ID = ?", new String[]{photo}, null);
					if(photoCursor != null && photoCursor.moveToFirst()){
						info.photos = photoCursor.getBlob(0);
					}
				} finally {
					photoCursor.close();
				}
			}
			info.isUnknow = false;
		}else{
			info.isUnknow = true;
		}
		info.displayName = address;
		cursor.close();
		return info;
	}
	
	public class PeopleInfo {
		private String displayName;
		private String lookUpKey;
		private boolean isUnknow;
		private byte[] photos;
		
		/**
		 * 绘制圆角
		 * @param data
		 * @return
		 */
		public Bitmap getPhotos(byte[] data){
			Bitmap bitm = null;
			if(photos != null && photos.length > 0)
				bitm = BitmapFactory.decodeByteArray(data, 0, data.length);
			else
				bitm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_header);
			
			Bitmap output = Bitmap.createBitmap(bitm.getWidth(), bitm.getHeight(), Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(output);
			canvas.drawARGB(0, 0, 0, 0);
			final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint.setAntiAlias(true);
			paint.setColor(0xff424242);
			final Rect rect = new Rect(0, 0, bitm.getWidth(), bitm.getHeight());
			final RectF rectf = new RectF(rect);
			canvas.drawRoundRect(rectf, ROUND, ROUND, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
			canvas.drawBitmap(bitm, rect, rect, paint);
			return output;
		}
	}
	
	final class ViewHolder {
		
		private ImageView header;
		private TextView name;
		private TextView date;
		private TextView content;
	}
}
